package com.dlc.felear.xiaoensale.utils;

import android.text.TextUtils;

import com.dlc.felear.xiaoensale.entity.WarnInfo;
import com.dlc.felear.xiaoensale.helper.OkHttpManager;
import com.itdlc.android.library.utils.APPDidUtil;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

import okhttp3.Call;

/**
 * Created by Administrator on 2018/4/3.
 */

public class UpLoadInfo {
    private static final String TAG = "UpLoadInfo";
    public static String LEVEL_DEBUG = "debug";
    /**
     * log
     */
    public static int TYPE_LOG = 0;
    /**
     * 网络
     */
    public static int STATUS_2 = 1;
    /**
     * 消息队列
     */
    public ArrayBlockingQueue<WarnInfo> queue;

    public static UpLoadInfo instance;

    public static UpLoadInfo getInstance() {
        if (instance == null) {
            synchronized (UpLoadInfo.class) {
                if (instance == null) {
                    instance = new UpLoadInfo();
                }
            }
        }
        return instance;
    }

    private UpLoadInfo() {
        queue = new ArrayBlockingQueue(30);
        runner();
    }

    /**
     * 发送日记信息到后台
     *
     * @param info
     * @param type
     */
    public void upLoadWarnInfo(String info, final int type) {
        if(TextUtils.isEmpty(info)){
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("deviceId", APPDidUtil.getAppDid());
        params.put("status", STATUS_2);
        params.put("type", type);
        params.put("machineType", 2);
        params.put("level", LEVEL_DEBUG);
        params.put("log", info);
        OkHttpManager.HttpPostJson(HttpApi.WARN, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
//                Log.e(TAG,"上传日记 Exception"+e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
//                Log.e(TAG,"上传日记"+response);
            }
        });
    }

    /**
     * 队列式发送
     *
     * @param info
     * @param type
     */
    public void syncSendWarnInfo(String info, final int type) {
        try {
            queue.put(new WarnInfo(info, type));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 消息轮询
     */
    private void runner() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    WarnInfo warnInfo = null;
                    // take位阻塞方法，取不到消息时会阻塞当前线程
                    while ((warnInfo = queue.take()) != null) {
                        upLoadWarnInfo(warnInfo.getMessage(), warnInfo.getType());
                        Thread.sleep(1000);
                    }
                } catch (Exception e) {
                }
            }
        }).start();
    }

}
